
<!--
 * @Descripttion: 授权登录
 * @version: 
 * @Author:Hui
 * @Date: 2022-11-29 17:36:17
 * @LastEditTime: 2025-09-17 18:17:37
 * @LastEditors: sueRimn
-->


<template>
  <view class="page">
    <view class="head">
      <image src="@/static/images/logo_3.png" class="logo" />
      <view class='t2'><text>点击授权登陆后,会弹出授权权限,请点击允许按钮.</text></view>
    </view>
    <view class="btns d-flex flex-column">

      <!-- #ifdef MP-WEIXIN -->
      <button type="primary" class='btn1' open-type="getPhoneNumber" @getphonenumber="handleGetPhone">手机号授权登录</button>
      <!-- #endif -->
       <!-- #ifdef MP-XHS -->
      <button type="primary" class='btn1' open-type="getPhoneNumber" @getphonenumber="handleGetPhone">手机号授权登录</button>
      <!-- #endif -->
      <!-- #ifdef MP-ALIPAY -->
      <button class='btn1' open-type="getPhoneNumber" @getphonenumber="handleAlipayPhone" onError="onAuthError"
        scope='phoneNumber'>
        手机号授权登录
      </button>
      <!-- #endif -->

      <button class="btn2" @click="uniRouter.navigateBack()">暂不授权</button>
    </view>



    <!-- 微信隐私授权 -->
    <!-- #ifdef MP-WEIXIN -->
    <ws-wx-privacy ref="wxPrivacyRef" id="privacy-popup" />
    <!-- #endif -->
  </view>
</template>

<script>

import { mapState } from 'vuex'
import { fetchProgramPhone, getUserSaveWxUserLocation } from '@/api'
import { getLocationAddress } from '@/utils'
import loadOpenid from '@/utils/smallAppOpenid'

export default {
  name: "Auth",
  computed: {
    ...mapState({
      parentId: state => state.user.parentId,
      openId: state => state.user.openId,
    })
  },
  data() {
    return {
      to_from: '',
    }
  },
  onLoad(option) {
    if (option.to_from) {
      this.to_from = option.to_from
    }
    console.log('本地没有存openId', this.openId)
    if (!this.openId) {
      this.handleGetOpenId()
    }
  },

  methods: {
    //获取用户openId
    async handleGetOpenId() {
      const result = await loadOpenid()
      if (result.code === 200) {
        this.$store.dispatch('user/updateOpenId', result.data)
      }
    },
    // 获取用户手机号回调
    async handleGetPhone(e) {
      const { detail } = e
      console.log(e)
      // if (!detail.code) { return }
      uni.showLoading({ title: '登录中', mask: true })
      const payload = {
        openId: this.openId,
        code: detail.code,
        encryptedData:detail.encryptedData,
        iv:detail.iv,
      }
      const r = await fetchProgramPhone(payload)
      if (r.code === 200) {
        if (r.data) {
          this.$store.dispatch('user/userLogin', r.data)
          setTimeout(() => {
            this.checkGo(r.data)
          }, 100)
        }
      } else {
        this.handleGetOpenId()
        uni.showModal({
          title: "授权失败,请重新授权登录. ",
          showCancel: false,
        })
      }
    },

    // #ifdef MP-ALIPAY
    // 支付宝手机号授权登录
    handleAlipayPhone(e) {
      const openid = uni.getStorageSync('openid')
      my.getPhoneNumber({
        success: async res => {
          uni.showLoading({ title: '登录中...', mask: true })
          if (res.response) {
            const payload = {
              openId: this.openId,
              parentId: this.parentId,
              code: res.response,
            }

            const r = await fetchProgramPhone(payload)

            if (r.code === 200) {
              if (r.data) {
                this.$store.dispatch('user/userLogin', r.data)
                setTimeout(() => {
                  this.checkGo(r.data)
                }, 100)
              }
            } else {
              this.handleGetOpenId()
              uni.showModal({
                title: "取消授权可能导致回收流程无法进行,请重新授权",
                showCancel: false,
              })
            }
          } else {
            uni.showModal({
              title: '提示',
              content: '用户授权失败',
              cancelText: '我知道了',
              confirmText: '重新授权',
            })
          }
        },
        fail: res => {
          // console.log(res)
          // console.log('getPhoneNumber_fail')
        }
      })
    },
    // #endif




    checkGo() {
      const pages = getCurrentPages()
      if (this.to_from) {
        uni.redirectTo({ url: this.to_from })
      } else {
        if (pages.length > 1) {
          uni.navigateBack()
        } else {
          uni.switchTab({ url: `/pages/user/index` })
        }
      }
    },

    // 判断是否保存过地址信息
    saveAddress(data) {
      const { hasAuthLocation } = data
      if (!hasAuthLocation) {
        getLocationAddress(this.location, (addressComponent) => {
          const { province, city } = addressComponent
          getUserSaveWxUserLocation({ province, city })
        })
      }
    },

    // 返回渠道号
    returnChannel() {
      const channel = getApp().globalData.channel
      const shareMerchantId = getApp().globalData.shareMerchantId

      if (channel && shareMerchantId) {
        return 'merchant'
      } else if (channel) {
        return channel
      }
      return 'platform'
    }
  }
}
</script>


<style lang="scss" scoped>
.page {
  background: #fff;
  min-height: 100vh;
  padding: 0 50rpx;

  .logo {
    display: block;
    width: 194rpx;
    height: 194rpx;
    overflow: hidden;
    border-radius: 50%;
    margin: 0rpx auto 24rpx;
  }

  .head {
    padding: 120rpx 0rpx 0rpx;
    text-align: center;

    .t2 {
      font-size: 26rpx;
      color: var(--hui-color-subtitle);
      line-height: 32rpx;
    }
  }

  .btns {
    .btn1 {
      padding: 0;
      margin: 120rpx 0 24rpx 0;
      border: 0;
      font-size: 30rpx;
      color: #fff;
      line-height: 96rpx;
      text-align: center;
      background: var(--hui-color-primary);
      border-radius: 50rpx;
      font-weight: bold;
    }

    .btn2 {
      padding: 0;
      margin: 0;
      border: 0;
      font-size: 30rpx;
      color: var(--hui-color-subtitle);
      line-height: 96rpx;
      text-align: center;
      background: #fff;
      border-radius: 50rpx;
      border: 1px solid #eee;
    }
  }
}
</style>